package rpg.core
{
	import flash.geom.ColorTransform;

	import rpg.data.FightState;
	import rpg.data.SpriteStat;
	import rpg.manager.DataManager;
	import rpg.role.Hero;

	public class BufferComponent extends AutoDestroyComponent
	{
		private var state : FightState;
		/**
		 * 需要更新次数
		 */
		public var totalFrames : int;
		/**
		 * 当前更新次数
		 */
		public var currFrameCount : int;
		/**
		 * 当前时间
		 */
		public var frameTime : int;
		/**
		 * 多长时间更新一次
		 */
		public var frameDelay : int;

		private var role : Hero;

		private var spriteStat : SpriteStat;

		public function BufferComponent(type : *)
		{
			super(type);
		}

		override public function notifyAdded() : void
		{
			role = owner as Hero;
		}

		override public function update(delay : uint) : void
		{
			palyElapsedTime += delay;
			if(palyElapsedTime >= duration)
			{
				timeOut();
			}
			if(currFrameCount < totalFrames)
			{
				frameTime += delay;
				if(frameTime >= frameDelay)
				{
					currFrameCount += 1;
				}
				if(state.hpPerTime)
					role.data.currHP += state.hpPerTime;
			}
		}

		public function setState(value : FightState) : void
		{
			state = value;
			if(!state)
				return;
			if(state.hush)
				role.isHush = true;
			if(state.fightable)
				role.fightable = true;
			if(state.movable)
				role.movable = true;
			if(state.invincibly > 0)
				role.invincibility = true;
			if(state.colorTransform)
			{
				var data : Array = state.colorTransform.split(",");
				var colorTransform : ColorTransform = new ColorTransform(data[0] , data[1] , data[2] , data[3] , data[4] , data[5] , data[6] , data[7]);
				role.avatarComponent.colorTransform = colorTransform;
			}
			if(state.spriteStat > 0)
			{
				var spriteStat : SpriteStat = DataManager.getInstance().globalSpriteState[state.spriteStat] as SpriteStat;
				if(!spriteStat)
					return;
				if(state.buffOrDebuff == 1)
				{
					role.data.baseState.addStat(spriteStat);
				}
				else
				{
					role.data.baseState.removeStat(spriteStat);
				}
			}
		}

		override public function timeOut() : void
		{
			if(state.hush)
				role.isHush = false;
			if(state.fightable)
				role.fightable = false;
			if(state.movable)
				role.movable = false;
			if(state.invincibly > 0)
				role.invincibility = false;
			if(state.colorTransform)
				role.avatarComponent.colorTransform = null;
			if(spriteStat)
			{
				if(state.buffOrDebuff == 0)
				{
					role.data.baseState.addStat(spriteStat);
				}
				else
				{
					role.data.baseState.removeStat(spriteStat);
				}
			}
			if(state.animation)
			{
				role.removeComponentByType(state.getAnimation().animationIndex);
			}
			super.destroy();
		}

		override public function destroy() : void
		{
			super.destroy();
			spriteStat = null;
			state = null;
			role = null;
		}


	}
}